<?php	
/* 
 * Copyright (C) 2012 Leah Rowe <info@minifree.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/*
 * This contains most common functions used by all of the OAchecker scripts.
 * Most crucial, contained here are functions for connecting to the database.
 */

// common variables (regular expressions)
$rxIPv4Addr = "/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-".
	"9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/";
$rxHostname = "/^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|".
	"[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$/";
$rxEmail = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{".
	"2,3})$/";

function dbConfig() {

	// IMPORTANT!!!!!!!!!!!!!
	// Make sure that the information here is correct
	
	// THIS IS THE DATA THAT YOU NEED IN ORDER TO ACCESS THE DATABASE
	// WITHOUT THESE SETTINGS PROPERLY IN PLACE, THIS SOFTWARE **WILL
	// NOT WORK**

	$db = "";
	
	$db["host"] = "";
	$db["database"] = "";
	$db["user"] = "";
	$db["password"] = "";
	
	return $db;
}

function inject($query) 
{
	$retval = "";
	
	$db = dbConfig();
	
	$host = $db["host"];
	$database = $db["database"];
	$user = $db["user"];
	$password = $db["password"];

	$con = mysql_connect($host,$user,$password);
	if (!$con)
	{
		die('Inject function Could not connect: ' . mysql_error());
	}

	mysql_select_db($database, $con);

	$retval = mysql_query($query);

	mysql_close($con);
	
	return $retval;	
}

function urlExists($url=NULL)  
{  
	if($url == NULL) return false;  
	
	$ch = curl_init($url);  
	
	curl_setopt($ch, CURLOPT_TIMEOUT, 5);  
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);  
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
	
	$data = curl_exec($ch);  
	$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
	
	curl_close($ch);  
	
	if($httpcode>=200 && $httpcode<300){  
		return true;  
	} else {  
		return false;  
	}  
}

function strip_html_tags( $text )
{
	$text = preg_replace(
	array(
	  // Remove invisible content
		"@<style[^>]*?>.*?</style>@siu",
		"@<head[^>]*?>.*?</head>@siu",
		"@<script[^>]*?.*?</script>@siu",
		"@<object[^>]*?.*?</object>@siu",
		"@<embed[^>]*?.*?</embed>@siu",
		"@<applet[^>]*?.*?</applet>@siu",
		"@<noframes[^>]*?.*?</noframes>@siu",
		"@<noscript[^>]*?.*?</noscript>@siu",
		"@<noembed[^>]*?.*?</noembed>@siu",
	  // Add line breaks before and after blocks
		"@</?((address)|(blockquote)|(center)|(del))@iu",
		"@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu",
		"@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu",
		"@</?((table)|(th)|(td)|(caption))@iu",
		"@</?((form)|(button)|(fieldset)|(legend)|(input))@iu",
		"@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu",
		"@</?((frameset)|(frame)|(iframe))@iu",
	),
	array(
		' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
		"\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0",
		"\n\$0", "\n\$0",
	),
	$text );
	return strip_tags( $text );
}

function clean($input) {

	$db = dbConfig();

	$host = $db["host"];
	$database = $db["database"];
	$user = $db["user"];
	$password = $db["password"];

	$con = mysql_connect($host,$user,$password);
	if (!$con)
	{
		die('Clean function Could not connect: ' . mysql_error());
	}

	mysql_select_db($database, $con);

	$output = $input;
	$output = strip_html_tags($output);
	$output = mysql_real_escape_string($output);

	mysql_close($con);

	return $output;
}

// record new log entry
function record($info,$section) 
{
	if (!isset($info)) return "info not set";
	if (!isset($section)) return "section not set";
	
	if (strlen($info) == 0) return "info not set";
	if (strlen($section) == 0) return "section not set";
	
	$info = clean($info);
	$section = clean($section);
	
	$ip = clean($_SERVER["REMOTE_ADDR"]);
	$hostname = clean(gethostbyaddr($ip));
	// info
	// section
	$user = "";
	if (isset($_SESSION["user"])) $user = clean($_SESSION["user"]);
	$timestamp = clean(date("U"));
	
	inject("INSERT INTO logs VALUES('$ip','$hostname','$info','$section',
		'$user','$timestamp')");
	return "";		
}

// send an email on behalf of...
function compose($subject, $message) 
{
	$sqlAdmin = inject("SELECT * FROM admin");
	$sqlAdminNrows = mysql_numrows($sqlAdmin);

	$subject .= " (OAchecker)";
	$message .= " \n\nTHIS IS AN AUTOMATED MESSAGE, PLEASE DO NOT ".
		"REPLY\n\n"; // please do
	
	for ($i = 0; $i < $sqlAdminNrows; $i++) {
		
		$sqlAdminEmailAddr = mysql_result($sqlAdmin, $i, "emailaddr");

		$from = $sqlAdminEmailAddr;
		$headers = "From: $from\r\nReply-To: $from\r\nX-Mailer: PHP/".
			phpversion();
		
		mail($sqlAdminEmailAddr, $subject, $message, $headers, "-f".
			$from);
	}
	
	if ($sqlAdminNrows > 0) return "emails sent";
	else return "no email admins listed, emails not sent";
}


// CRON FUNCTIONS
// (but could be used for other purposes)

function curlGetPage($page) {
	$content = "";

	$ch = curl_init($page);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
	$content = curl_exec($ch);
	curl_close($ch);
	
	return $content;
}

function serverArray()
{
	// MySQL data
	$sqlServers = inject("SELECT * FROM servers");
	$sqlServersNrows = mysql_numrows($sqlServers);
	
	// ip:port
	$serversFull = array($sqlServersNrows);
	
	// ip
	$serversIPAddr = array($sqlServersNrows);
	
	// port
	$serversPortNum = array($sqlServersNrows);
	
	// serverdown
	$serversServerDown = array($sqlServersNrows);
	
	for ($i = 0; $i < $sqlServersNrows; $i++) 
	{
		$sqlServersIPAddr = mysql_result($sqlServers, $i, "ipaddr");
		$sqlServersPortNum = mysql_result($sqlServers, $i, "portnum");
		$sqlServersServerDown = mysql_result($sqlServers, $i,
			"serverdown");
		
		// Full form ip:port array
		$serversFull[$i] = "$sqlServersIPAddr:$sqlServersPortNum";
		
		// Individual items
		$serversIPAddr[$i] = "$sqlServersIPAddr";
		$serversPortNum[$i] = "$sqlServersPortNum";
		$serversServerDown[$i] = "$sqlServersServerDown";
	}

	$server = "";
	
	$server["full"] = $serversFull;
	$server["ipaddr"] = $serversIPAddr;
	$server["portnum"] = $serversPortNum;
	$server["serverdown"] = $serversServerDown;
	
	return $server;
}

function qstatArray()
{
	$sqlQStat = inject("SELECT * FROM qstat");
	$sqlQStatNrows = mysql_numrows($sqlQStat);
	
	// Content of each QStat page
	$qstatContent = array($sqlQStatNrows);
	
	// URL of each QStat page
	$qstatListURL = array($sqlQStatNrows);
	
	for ($i = 0; $i < $sqlQStatNrows; $i++)
	{
		$sqlQStatListURL = mysql_result($sqlQStat, $i, "listurl");
		
		$qstatContent[$i] = curlGetPage($sqlQStatListURL);
		$qstatListURL[$i] = $sqlQStatListURL;
	}
	
	$qstat = "";
	$qstat["listurl"] = $qstatListURL;
	$qstat["content"] = $qstatContent;
	
	return $qstat;
}
?>
